<?php
/**
 * $Id: request.php 21 2009-06-10 02:24:31Z eyou80 $
 */

/** 载入支持 **/
require_once 'tinyask/request.php';

/**
 * 应用的请求类
 *
 * @package App
 */
class Tinyask_App_Request extends Tinyask_Request
{
	/**
	 * 刷新后的参数
	 *
	 * @var array
	 */
	private $_params = array();

	/**
	 * 是否刷新请求参数
	 *
	 * @var boolean
	 */
	private $_flushed = false;

	/**
	 * 当前过滤器
	 *
	 * @var array
	 */
	private $_filter = array();

	/**
	 * 默认值
	 *
	 * @var mixed
	 */
	private $_default = null;

	/**
	 * 支持的过滤器列表
	 *
	 * @var array
	 */
	private static $_supportedFilters = array(
		'int' => 'intval',
		'integer' => 'intval',
		'search' => array('Tinyask_Common', 'searchFilter'),
		'xss' => array('Tinyask_Common', 'xssFilter'),
		'url' => array('Tinyask_Common', 'urlFilter')
	);

	/**
	 * 应用过滤器
	 *
	 * @param mixed $value
	 * @return mixed
	 */
	private  function _applyFilter($value)
	{
		if($this->_filter) {
			foreach ($this->_filter as $filter) {
				$value = is_array($value) ? array_map($filter, $value) : call_user_func($filter, $value);
			}
		}

		$this->_filter = array();
		return $value;
	}

	/**
	 * 刷新请求参数
	 *
	 * @param mixed $params
	 */
	public function flush($params)
	{
		$this->_flushed = true;

		$args = $params;
		if(is_string($params)) {
			parse_str($params, $args);
		}

		$this->_params = $args;
	}

	/**
	 * 设置默认值
	 *
	 * @param mixed $value
	 * @return Tinyask_App_Request
	 */
	public function setDefault($value)
	{
		$this->_default = $value;
		return $this;
	}

	/**
	 * 设置过滤器
	 *
	 * @return Tinyask_App_Request
	 */
	public function filter()
	{
		$filters = func_get_args();

		foreach ($filters as $filter) {
			$this->_filter[] = is_string($filter) && isset(self::$_supportedFilters[$filter]) ? self::$_supportedFilters[$filter] : $filter;
		}
		return $this;
	}

	/**
	 * 获取参数列表
	 *
	 * @param mixed $param
	 * @return array
	 */
	public function from($param)
	{
		$params = array();
		if(is_array($param)) {
			$args = $param;
		}  else {
			$args = func_get_args();
		}
		foreach ($args as $name) {
			$params[$name] = $this->{$name};
		}
		return $params;
	}

	/**
	 * 获取指定参数值
	 *
	 * @param string $name
	 * @return mixed
	 */
	public function __get($name)
	{
		if($this->_flushed) {
			$value = isset($this->_params[$name]) ? $this->_params[$name] : $this->_default;
		}  else {
			$value = parent::getParam($name, $this->_default);
		}

		$this->_default = null;
		return $this->_filter ? $this->_applyFilter($value) : $value;
	}

	/**
	 * 设定指定参数
	 *
	 * @param string $name
	 * @param mixed $value
	 */
	public function __set($name, $value)
	{
		if($this->_flushed) {
			$this->_params[$name] = $value;
		}  else {
			parent::setParam($name, $value);
		}
	}

	/**
	 * 判断指定参数是否存在
	 *
	 * @param string $name
	 * @return boolean
	 */
	public function __isset($name)
	{
		if($this->_flushed) {
			return isset($this->_params[$name]);
		}  else {
			return parent::issetParam($name);
		}
	}
}
